package it.polimi.travelDream.ejb.beans;

import java.util.List;

import it.polimi.travelDream.ejb.Cthulhu.Persistenza;
import it.polimi.travelDream.ejb.interfaces.CartMgrRemote;
import it.polimi.travelDream.entities.Cart;


import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;


@Stateless
@LocalBean

public class CartMgr implements CartMgrRemote {
	/**
	 * @author Filipazzi,Crisciullo
	 * CartMgr implements the CartMgrRemote interface.
	 * It contains the methods to manage the cart functions
	 */
	Persistenza persist=new Persistenza();
	public EntityManagerFactory factory;
	public EntityManager em;
	Cart cart;

	
    public CartMgr() {
        // TODO Auto-generated constructor stub
    }

    
    /**
	 * @author Filipazzi,Crisciullo
	 * CartMgr implements the CartMgrRemote.
	 * It shows packges in user's cart. 
	 * It gets the user's id as parameter.
	 */
    @Override
	public List<Cart> showAllCart(int id){
		factory=Persistence.createEntityManagerFactory("it.polimi.travelDream");
		em=factory.createEntityManager();

		TypedQuery<Cart> query = em.createQuery("SELECT c FROM Cart c WHERE c.idUser="+id+"", Cart.class);

			List<Cart> cart = query.getResultList();

			em.close();
			factory.close();
			return cart;
	}
    /**
	 * @author Filipazzi,Crisciullo
	 * This method adds a package to the cart.
	 */
	@Override
	public Cart addToCart(Cart cart) {
		// TODO Auto-generated method stub
		persist.persista(cart);
		return cart;
	}

	@Override
	public void emptyCart() {
		// TODO Auto-generated method stub
		
	}

	 /**
		 * @author Filipazzi,Crisciullo
		 * This method remove a package from the cart.
		 */
	@Override
	public void removeFromCart(int id) {
		factory=Persistence.createEntityManagerFactory("it.polimi.travelDream");
		em=factory.createEntityManager();
		Cart cart = em.find(Cart.class, id);
		em.getTransaction().begin();
		em.remove(cart);
		em.getTransaction().commit();
		em.close();
		factory.close();
	}

	@Override
	public void buy() {
		// TODO Auto-generated method stub
		
	}


}
